<template>
  <div class="file-table-wrapper">
    <!-- 文件表格 -->
    <el-table
      ref="multipleTable"
      v-loading="tableLoading"
      class="file-table"
      fit
      element-loading-text="数据加载中"
      tooltip-effect="dark"
      :data="tableData_"
      height="100px"
      v-el-height-adaptive-table="{bottomOffset: 110}"
      @select-all="selectAllFileRow"
      @select="selectFileRow"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label prop="dir" width="60">
        <template slot-scope="scope">
          <img :src="setFileImg(scope.row.contentType)" style="width: 30px;">
        </template>
      </el-table-column>
      <el-table-column prop="originalFilename" show-overflow-tooltip>
        <template slot="header">
          <span>文件名</span>
          <el-input
            v-model="fileNameSearch"
            size="mini"
            style="width: 200px;display: inline-block;float:right;margin-right: calc(100% - 294px);"
            placeholder="输入文件名搜索"
          />
        </template>
        <template slot-scope="scope">
          <div style="cursor:pointer;" @click="clickFileName(scope.row)">
            <span>{{ scope.row.originalFilename }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="类型" width="100" prop="contentType" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="scope.row.contentType">{{ scope.row.contentType }}</span>
          <span v-else>文件夹</span>
        </template>
      </el-table-column>
      <el-table-column align="right" label="大小" prop="fileSize" width="100" show-overflow-tooltip>
        <template slot-scope="scope">
          <div style="padding: 0 10px;">{{ calculateFileSize(scope.row.fileSize) }}</div>
        </template>
      </el-table-column>
      <el-table-column align="right" label="修改日期" prop="uploadTime" width="160" show-overflow-tooltip />
      <el-table-column :width="operaColumnWidth" align="right" width="100" fixed="right">
        <template slot-scope="scope">
          <el-dropdown>
            <el-button>
              操作<i class="el-icon-arrow-down el-icon--right" />
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-if="scope.row.contentType">
                <el-link :underline="false" icon="el-icon-data-line" type="warning" @click.native="editFile(scope.row)">在线编辑</el-link>
              </el-dropdown-item>
              <el-dropdown-item v-if="scope.row.contentType && isZipFile(scope.row.contentType)">
                <el-link :underline="false" icon="el-icon-folder-opened" type="success" @click.native="unzipFile(scope.row)">解压</el-link>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-link :underline="false" icon="el-icon-folder-remove" type="success" @click.native="showMoveFileDialog(scope.row)">移动</el-link>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-link :underline="false" icon="el-icon-document-delete" type="danger" @click.native="deleteFile(scope.row)">删除</el-link>
              </el-dropdown-item>
              <el-dropdown-item v-if="scope.row.dir === false">
                <el-link :underline="false" icon="el-icon-download" type="primary" :href="downloadUrl(scope.row.path)">下载</el-link>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="tableQuery.total>0" :total="tableQuery.total" :page.sync="tableQuery.page" :limit.sync="tableQuery.limit" @pagination="getTableData" />
  </div>
</template>

<script>
import { fileTable, fileManageDelete, unzipFile } from '@/api/tool/file'

export default {
  name: 'FileManageTable',
  data() {
    return {
      storageValue: 0,
      fileNameSearch: '',
      tableLoading: false,
      tableData: [],
      tableQuery: {
        page: 1,
        limit: 20,
        total: 0,
        sort: undefined,
        order: undefined
      },
      // 移动文件模态框数据
      dialogMoveFile: {
        isBatchMove: false,
        visible: false, // 是否可见
        fileTree: [], // 目录树
        defaultProps: {
          children: 'children',
          label: 'label'
        }
      },
      //  可以识别的文件类型
      fileImgTypeList: [
        'png',
        'jpg',
        'jpeg',
        'docx',
        'doc',
        'ppt',
        'pptx',
        'xls',
        'xlsx',
        'avi',
        'mp4',
        'css',
        'csv',
        'chm',
        'rar',
        'zip',
        'dmg',
        'mp3',
        'open',
        'pdf',
        'rtf',
        'txt',
        'oa',
        'js',
        'html',
        'img',
        'sql',
        'jar',
        'svg',
        'gif',
        'json',
        'exe'
      ],
      //  文件图片Map映射
      fileImgMap: {
        dir: require('@/assets/images/file/dir.png'),
        chm: require('@/assets/images/file/file_chm.png'),
        css: require('@/assets/images/file/file_css.png'),
        csv: require('@/assets/images/file/file_csv.png'),
        png: require('@/assets/images/file/file_pic.png'),
        jpg: require('@/assets/images/file/file_pic.png'),
        jpeg: require('@/assets/images/file/file_pic.png'),
        docx: require('@/assets/images/file/file_word.png'),
        doc: require('@/assets/images/file/file_word.png'),
        ppt: require('@/assets/images/file/file_ppt.png'),
        pptx: require('@/assets/images/file/file_ppt.png'),
        xls: require('@/assets/images/file/file_excel.png'),
        xlsx: require('@/assets/images/file/file_excel.png'),
        mp4: require('@/assets/images/file/file_video.png'),
        avi: require('@/assets/images/file/file_avi.png'),
        rar: require('@/assets/images/file/file_rar.png'),
        zip: require('@/assets/images/file/file_zip.png'),
        dmg: require('@/assets/images/file/file_dmg.png'),
        mp3: require('@/assets/images/file/file_music.png'),
        open: require('@/assets/images/file/file_open.png'),
        pdf: require('@/assets/images/file/file_pdf.png'),
        rtf: require('@/assets/images/file/file_rtf.png'),
        txt: require('@/assets/images/file/file_txt.png'),
        oa: require('@/assets/images/file/file_oa.png'),
        js: require('@/assets/images/file/file_js.png'),
        html: require('@/assets/images/file/file_html.png'),
        img: require('@/assets/images/file/file_img.png'),
        sql: require('@/assets/images/file/file_sql.png'),
        jar: require('@/assets/images/file/file_jar.png'),
        svg: require('@/assets/images/file/file_svg.png'),
        gif: require('@/assets/images/file/file_gif.png'),
        json: require('@/assets/images/file/file_json.png'),
        exe: require('@/assets/images/file/file_exe.png'),
        unknown: require('@/assets/images/file/file_unknown.png')
      }
    }
  },
  computed: {
    //  当前查看的文件路径
    filePath: {
      get() {
        return this.$route.query.filePath
      },
      set() {
        return ''
      }
    },
    //  过滤后的表格数据
    tableData_() {
      return this.tableData.filter(
        data =>
          !this.fileNameSearch ||
          data.originalFilename
            .toLowerCase()
            .includes(this.fileNameSearch.toLowerCase())
      )
    },
    //  判断当前路径下是否有普通文件
    isIncludeNormalFile() {
      return this.tableData.map(data => data.dir).includes(0)
    },
    //  判断当前路径下是否有压缩文件
    isIncludeZipRarFile() {
      return (
        this.tableData.map(data => data.contentType).includes('zip') ||
        this.tableData.map(data => data.contentType).includes('rar')
      )
    },
    operaColumnWidth() {
      return this.isIncludeZipRarFile ? 300 : 220
    },
    downloadUrl() {
      return function(value) {
        return encodeURI(this.$store.state.app.server_api + `${process.env.VUE_APP_MODULE_ADMIN_API}/api/file/download?path=${value}`)
      }
    },
    isOfficeFile() {
      return function(value) {
        return value.indexOf('doc') !== -1 || value.indexOf('xls') !== -1 || value.indexOf('ppt') !== -1 || value.indexOf('pdf') !== -1
      }
    },
    isZipFile() {
      return function(value) {
        return value.indexOf('zip') !== -1 || value.indexOf('rar') !== -1
      }
    }
  },
  methods: {
    getTableData(init) {
      if (init === true) {
        this.tableQuery.page = 1
        this.tableQuery.limit = 20
        this.tableQuery.total = 0
      }
      const queryData = {
        id: this.filePath,
        file_only: false
      }
      const query = Object.assign(this.tableQuery, queryData)
      this.tableLoading = true
      this.$emit('setSelectionFile', [])
      fileTable(query).then(response => {
        this.tableData = response.param.data
        this.tableQuery.total = response.param.recordsTotal
        this.tableLoading = false
      }).catch(e => {
        this.tableLoading = false
      })
    },
    // 根据文件扩展名设置文件图片
    setFileImg(extendName) {
      if (extendName === null) {
        // 文件夹
        return this.fileImgMap.dir
      } else if (!this.fileImgTypeList.includes(extendName)) {
        // 无法识别文件类型的文件
        return this.fileImgMap.unknown
      } else {
        // 可以识别文件类型的文件
        return this.fileImgMap[extendName]
      }
    },
    // 计算文件大小
    calculateFileSize(size) {
      const B = 1024
      const KB = Math.pow(1024, 2)
      const MB = Math.pow(1024, 3)
      const GB = Math.pow(1024, 4)
      if (!size) {
        return '_'
      } else if (size < KB) {
        return (size / B).toFixed(0) + 'KB'
      } else if (size < MB) {
        return (size / KB).toFixed(1) + 'MB'
      } else if (size < GB) {
        return (size / MB).toFixed(2) + 'GB'
      } else {
        return (size / GB).toFixed(3) + 'TB'
      }
    },
    // 点击文件名
    clickFileName(row) {
      if (row.dir === true) {
        // 若是目录则进入目录
        this.$router.push({
          query: {
            filePath: row.localPath
          }
        })
        this.$emit('getTableData')
        this.$emit('showStorage')
      } else {
        let url = this.$store.state.app.server_api + `${process.env.VUE_APP_MODULE_ADMIN_API}/office/preview?path=` + encodeURI(row.localPath)
        if (this.isOfficeFile(row.contentType)) {
          url += '&isOffice=true'
        }
        url += '&access_token=' + this.$store.state.user.token
        // 若是文件，则进行相应的预览
        //弹窗宽度和长度，自己看情况调整
        let width = (screen.availWidth/3)*2
        let height = (screen.availHeight/3)*2
        let left = (screen.availWidth-width)/2
        let top = (screen.availHeight-height)/2
        let param = 'scrollbars=auto,width=' + width + ',height=' + height + "',left=" + left + ',top=' + top
        window.open(url,'查看文件', param)
        //window.open(url, '查看文件', '_blank')
      }
    },
    selectAllFileRow(selection) {
      this.$emit('setSelectionFile', selection)
    },
    selectFileRow(selection) {
      this.$emit('setSelectionFile', selection)
    },
    // 操作列-移动按钮：打开移动文件模态框
    showMoveFileDialog(file) {
      // 第一个参数: 是否批量移动；第二个参数：打开/关闭移动文件模态框
      this.$emit('setOperationFile', file)
      this.$emit('showFileTreeDialog', false)
    },
    // 操作列-删除按钮
    deleteFile(fileInfo) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.confirmDeleteFile(fileInfo)
      }).catch(() => {})
    },
    // 删除文件模态框-确定按钮
    confirmDeleteFile(fileInfo) {
      fileManageDelete({ path: fileInfo.localPath }).then(response => {
        this.$message({
          type: 'success',
          message: response.msg
        })
        this.$emit('getTableData')
        this.$emit('showStorage')
      }).catch(() => {})
    },
    editFile(fileInfo) {
      let url = this.$store.state.app.server_api + `${process.env.VUE_APP_MODULE_ADMIN_API}/office/edit?path=` + encodeURI(fileInfo.localPath)
      if (this.isOfficeFile(fileInfo.contentType)) {
        url += '&isOffice=true'
      }
      url += '&access_token=' + this.$store.state.user.token
      // window居中打开自适应高度新窗口
      let iTop = (window.screen.availHeight)/2
      let iLeft = (window.screen.availWidth)/2
      window.open(url, '_blank', 'top=' + iTop + ',left=' + iLeft +',height=600')
      //window.open(url, '_blank')
    },
    // 解压文件
    unzipFile(fileInfo) {
      unzipFile({ path: fileInfo.localPath }).then(response => {
        this.$modal.msgSuccess(response.msg)
        this.$emit('getTableData')
        this.$emit('showStorage')
      }).catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
.file-table-wrapper {
  margin-top: 2px;
  .file-table {
    width: 100% !important;
    .el-table__header-wrapper {
      .el-icon-circle-plus, .el-icon-remove {
        margin-left: 6px;
        cursor: pointer;
        font-size: 16px;
        &:hover {
          color: #409EFF;
        }
      }
    }
    .el-table__body-wrapper {
      overflow-y: auto;
    }
  }
  .img-review-wrapper {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    overflow: auto;
    width: 100%;
    height: 100%;
    z-index: 4000;
    text-align: center;
    display: flex;
    align-items: center;
    animation: imgReviewAnimation 0.3s;
    -webkit-animation: imgReviewAnimation 0.3s; /* Safari and Chrome */
    animation-iteration-count: 0.3;
    -webkit-animation-iteration-count: 0.3;
    animation-fill-mode: forwards;
    -webkit-animation-fill-mode: forwards; /* Safari 和 Chrome */
    @keyframes imgReviewAnimation {
      0% {
        background: transparent;
      }
      100% {
        background: rgba(0, 0, 0, 0.8);
      }
    }
    @keyframes imgReviewAnimation {
      0% {
        background: transparent;
      }
      100% {
        background: rgba(0, 0, 0, 0.8);
      }
    }
    .img-large {
      margin: 0 auto;
      max-width: 80%;
      max-height: 100%;
    }
  }
}
</style>
